from django.shortcuts import render

# Create your views here.

from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets, authentication
from rest_framework.pagination import PageNumberPagination
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from rest_framework.permissions import IsAuthenticated

from competition.models import CompetitionSeason
from competition.serializers import CompetitionListSerializer,CompetitionCreateSerializer


class CompetitionPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = "page"


class CompetitionViewSet(viewsets.ModelViewSet):
    """
        赛季信息
        list:
            获取赛季信息
        create:
            添加赛季信息
        retrieve:
            获取单独赛季信息
        update:
            全部更新赛季信息
        partial_update:
            部分更新赛季信息
        delete:
            删除赛季信息
    """

    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)  # jwt和session认证
    pagination_class = CompetitionPagination  # 分页
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)  # 过滤，一般为choice和外键
    # filter_class = CompetitionFilter
    search_fields = ('competition_name', 'holding_time')  # 搜索，文字字段

    def get_serializer_class(self):
        if self.action in ["create","partial_update"]:
            return CompetitionCreateSerializer
        return CompetitionListSerializer

    def get_permissions(self):  # 动态获取权限
        if self.action in ["list", "retrieve"]:  # 查看赛季不需要登录
            return []
        return [IsAuthenticated()]

    def get_queryset(self):
        return CompetitionSeason.objects.filter(is_active=1)
